import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutterdemo/1demo/common/common.dart';
import 'package:flutterdemo/1demo/common/event.dart';
import 'package:flutterdemo/1demo/common/utils/local_storage_util.dart';
import 'package:flutterdemo/1demo/constants/color_constants.dart';
import 'package:flutterdemo/1demo/constants/string_constants.dart';
import 'package:flutterdemo/1demo/model/get_response_model1.dart';
import 'package:flutterdemo/1demo/model/open_api_user_response_mode.dart';
import 'package:flutterdemo/1demo/model/post_response_model1.dart';
import 'package:flutterdemo/1demo/network/address.dart';
import 'package:flutterdemo/1demo/network/data_helper.dart';
import 'package:flutterdemo/1demo/network/http_manager.dart';
import 'package:flutterdemo/1demo/network/result_data.dart';
import 'package:flutterdemo/1demo/pages/login_web_page.dart';
import 'package:flutterdemo/1demo/pages/profile_detail_page.dart';

import 'my_message_page.dart';

class ProfilePage extends StatefulWidget {
  @override
  _ProfilePageState createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  final List menuTitles = AppStrings.PROFILE_MENU_TITLES;
  final List menuIcons = [
    Icon(Icons.message),
    Icon(Icons.message),
    Icon(Icons.message),
    Icon(Icons.message),
    Icon(Icons.message),
    Icon(Icons.message),
    Icon(Icons.message),
  ];

  String _userAvatarUrl;
  String _userNickname;

  @override
  void initState() {
    super.initState();
    isLogin().then((isLogin) {
      if (isLogin) {
        _getUserInfo();
      }
    });
    eventBus.on<LoginEvent>().listen((event) {
      print("登陆成功事件");
      _getUserInfo();
    });
    eventBus.on<LogoutEvent>().listen((event) {});
  }

  @override
  Widget build(BuildContext context) {
    return ListView.separated(
        itemBuilder: (context, index) {
          if (index == 0) {
            return buildHeader();
          } else {
            index -= 1;
            return InkWell(
              onTap: (){
                isLogin().then((isLogin) async {
                  if (isLogin) {
                    switch (index) {
                      case 0:
                        Navigator.of(context).push(MaterialPageRoute(builder: (context) => MyMessagePage()));
//                        String accessToken = await LocalStorageUtil.getString(LocalData.ACCESS_TOKEN);
//                        Map<String, dynamic> params = Map<String, dynamic>();
//                        params['dataType'] = 'json';
//                        params['page'] = 1;
//                        params['pageSize'] = 100;
//                        params['access_token'] = accessToken;
//                        HttpManager.getInstance(baseUrl: "").get(AppUrls.MESSAGE_LIST, params);
                        break;
                    }
                  } else {
                    _login();
                  }
                });
              },
              child: Container(
                height: 60,
                child: ListTile(
                  leading: menuIcons[index],
                  title: Text(menuTitles[index]),
                  trailing: Icon(Icons.arrow_forward_ios),
//                onTap: () {
//
//                },
                ),
              ),
            );
          }
        },
        separatorBuilder: (context, index) {
          return Container(
            margin: EdgeInsets.only(left: 10, right: 10),
            child: Divider(
              height: 0.9,
//            color: Color(0xffff0000),
            ),
          );
        },
        itemCount: menuTitles.length + 1);
  }

  Container buildHeader() {
    return Container(
      height: 150,
      color: Color(AppColors.APP_PRIMARY_COLOR),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            GestureDetector(
//                    onTap: _testPost,
              onTap: () {
                isLogin().then((isLogin) {
                  if (isLogin) {
                    Navigator.of(context).push(MaterialPageRoute(builder: (context) => ProfileDetailPage()));
                  } else {
                    _login();
                  }
                });
              },
              child: Container(
                width: 60,
                height: 60,
                decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    border: Border.all(color: Color(AppColors.WHITE), width: 2),
                    image: (_userAvatarUrl == null || _userAvatarUrl.isEmpty)
                        ? DecorationImage(image: AssetImage("assets/images/ic_avatar_default.png"), fit: BoxFit.cover)
                        : DecorationImage(image: NetworkImage(_userAvatarUrl), fit: BoxFit.cover)),
              ),
            ),
            SizedBox(
              height: 10,
            ),
            Text(
              _userNickname ??= '点击头像登陆',
              style: TextStyle(fontSize: 18, color: Color(AppColors.WHITE)),
            )
          ],
        ),
      ),
    );
  }

  Future<void> _testPost() async {
    var params = DataHelper.getBaseMap();
    params.clear();
    params["page"] = "1";
    params["count"] = "5";
    ResultData res = await HttpManager.getInstance(baseUrl: "").post(Address.POST_API1, params);
    PostResponseModel1 model = PostResponseModel1.fromJson(res.data);
    print(model.result[0].image);
  }

  Future<void> _testGet() async {
    var params = DataHelper.getBaseMap();
    params.clear();
    params["sid"] = "28654780";
    ResultData res = await HttpManager.getInstance(baseUrl: "").get(Address.GET_API1, params);
    GetResponseModel1 model = GetResponseModel1.fromJson(res.data);
    print(model.result.text);
  }

  void _login() async {
    final result = await Navigator.of(context).push(MaterialPageRoute(builder: (context) => LoginWebPage()));
    if (result != null && "refresh" == result) {
      // 通知event登陆成功事件
      Future.delayed(Duration(milliseconds: 100), _fireLoginEvent);
    }
  }

  Future<void> _fireLoginEvent() {
    eventBus.fire(LoginEvent());
    return null;
  }

  Future<void> _getUserInfo() async {
    sleep(Duration(milliseconds: 1000));
    String accessToken = await LocalStorageUtil.getString(LocalData.ACCESS_TOKEN);
    print("accessToken == $accessToken");
    if (accessToken == null || accessToken.length == 0) {
      return;
    }
    var params = DataHelper.getBaseMap();
    params.clear();
    params["access_token"] = accessToken;
    params["dataType"] = "json";

    ResultData res = await HttpManager.getInstance(baseUrl: "").get(AppUrls.OPENAPI_USER, params);

    OpenApiUserResponseModel model = OpenApiUserResponseModel.fromJson(res.data);
    setState(() {
      _userAvatarUrl = model.avatar;
      _userNickname = model.name;
    });
  }
}
